app.config(function($routeProvider, $locationProvider) {

	$routeProvider.when('/archives', {
		templateUrl: "archives/list.html",
		controller: 'archivesController'
	}).
	when('/archives/edit/:code', {
			templateUrl: 'archives/edit.html',
			controller: 'archivesEditController'
		});

});

function archivesService($http, $location) {

	return {

		add: function(data, manageId,app_id, recall) {
	   		//console.log(manageId)
			var create = 0;
			if (arguments.length == 4 && arguments[3] == 'create') {
				create = 1;
			}
			birthday = angular.element('#birthday').val(); //根据id绑定值
			var data = {
				name: data.name,
				cardid: data.cardid,
                attribute:data.attribute,
				sex: data.sex,
				birthday: birthday,
				phone_mob: data.phone_mob,
				phone_home: data.phone_home,
				xingzheng: data.xingzheng_title,
				xingzheng_code:(data != ''&& data != undefined && data.xingzheng_code!=undefined)?data.xingzheng_code:'',
	            xingzheng_title:(data != ''&& data != undefined && data.xingzheng_title!=undefined)?data.xingzheng_title:'',
				jiedao: data.jiedao_title,
				jiedao_code:(data != ''&& data != undefined && data.jiedao_code!=undefined)?data.jiedao_code:'',
	            jiedao_title:(data != ''&& data != undefined && data.jiedao_title!=undefined)?data.jiedao_title:'',
				shequ: data.shequ_title,
				shequ_code:(data != ''&& data != undefined && data.shequ_code!=undefined)?data.shequ_code:'',
	           	shequ_title:(data != ''&& data != undefined && data.shequ_title!=undefined)?data.shequ_title:'',
				address: data.address,
				create: create,
				manageId : manageId
			};
			baas_yl.call({
				'http': $http,
				'method': 'post',
				'uri': 'archives/archives/edit',
				'data': data,
				'success': function(d) {
					if (d.status == '1') {
						if (typeof recall == 'function') {
							recall(d);
						}
					} else {
						if (d.description) {
							alert(d.description);
						} else {
							alert('网络原因，请求失败，请稍后重试');
						}

					}
				}
			});
		},
		list: function(limit, page, app_id, fn) {
			var param = {
				limit: limit,
				page: page
			};
			baas_yl.call({
				'http': $http,
				'method': 'get',
				'uri': 'archives/archives/list',
				'data': param,
				'success': function(d) {
					if (typeof fn == 'function') {
						fn(d);
					}
				}
			});

		},
		find_one: function(code, app_id, fn) {

			baas_yl.call({
				'http': $http,
				'method': 'get',
				'uri': 'archives/archives/code/' + code,
				'success': function(d) {
					if (typeof fn == 'function') {
						fn(d);
					}
				}
			});
		},
		delete: function(code, app_id, fn) {

			var data = {
				code: code
			};
			baas_yl.call({
				'http': $http,
				'method': 'post',
				'uri': 'archives/archives/delete',
				'data': data,
				'success': function(d) {
					if (typeof fn == 'function') {
						fn(d);
					}
				}
			});

		},
		getRegion: function(code, app_id, fn) {
			baas_yl.call({
				'http': $http,
				'method': 'get',
				'uri': 'console/address/list/'+code,
				'success': function(d) {
					if (typeof fn == 'function') {
						fn(d);
					}
				}
			});

		},
		getStreet: function(code,app_id, fn) {
			baas_yl.call({
				'http': $http,
				'method': 'get',
				'uri': 'console/address/list/'+code,
				'success': function(d) {
					if (typeof fn == 'function') {
						fn(d);
					}
				}
			});

		},
		getArea: function(code,app_id, fn) {
			baas_yl.call({
				'http': $http,
				'method': 'get',
				'uri': 'console/address/list/'+code,
				'success': function(d) {
					if (typeof fn == 'function') {
						fn(d);
					}
				}
			});

		},
		search: function(search,limit, page,  app_id, fn) {
			var param = {
				limit : limit,
				page : page,
				name: ( search.eldername != ''&& search.eldername != undefined) ? search.eldername : undefined,
				phone: (search.phone !='' && search.phone != undefined) ? search.phone : undefined,
				em_name: ( search.em_name !='' && search.em_name != undefined) ? search.em_name : undefined,
				em_phone: (search.em_phone  !='' && search.em_phone != undefined) ? search.em_phone : undefined,
				card_number: ( search.card_number !='' && search.card_number != undefined) ? search.card_number : undefined,
				fund: ( search.fund !='' && search.fund != undefined) ? search.fund : undefined,
				jiedao: ( search.jiedao_title !='' && search.jiedao_title != undefined) ? search.jiedao_title : undefined,
				cardid: ( search.cardid !='' && search.cardid != undefined) ? search.cardid : undefined
			};

			baas_yl.call({
				'http': $http,
//				'method': 'post',
				'method': 'get',
//				'uri': 'archives/archives/search',
				'uri': 'archives/archives/list',
				'data': param,
				'success': function(d) {
					if (typeof fn == 'function') {
						fn(d);
					}
				}
			});
		}
		,import : function(  path,app_id, fn ){
            data = {
                path : path
            };
			baas_yl.call({
				'http': $http,
				'method': 'post',
				'uri': 'archives/archives/import',
				'data': data,
				'success': function(d) {
					if (typeof fn == 'function') {
						fn(d);
					}
				}
			});
        }
	};
}

app.factory('archivesService', ['$http', '$location', archivesService]);

app.controller('archivesController', ['$scope', '$routeParams', '$window', '$location', '$http', 'archivesService', archivesController]);

app.controller('archivesEditController', ['$scope', '$routeParams', '$window', '$location', '$http', 'archivesService','orderService','callCenterService', archivesEditController]);


function archivesController($scope, $routeParams, $window, $location, $http, archivesService) {


	$scope.app_id = $routeParams.app_id;
	$scope.selectedPage = $routeParams.page;

	$scope.selectedPage = 1;
	$scope.data = {
		selectedPage: $scope.selectedPage,
		page: $scope.page
	};
	$scope.limit = 20;
	$scope.getList = function() {
		archivesService.list($scope.limit, $scope.selectedPage, $scope.app_id, function(json) {
			$scope.list = json['list'];
			$scope.count = json.count;
			$scope.currentPage = 1;
			$scope.getPage(json.count);
		});
	};
	$scope.currentYear = getCurrentYear();
	$scope.getList();
	$scope.search = {};
	$scope.searchArchives = function() {
        $scope.selectedPage = 1;
		$scope.limit = 20;
		archivesService.search($scope.search, $scope.limit, $scope.selectedPage, $scope.app_id, function(json) {
			$scope.list = json['list'];
			$scope.count = json['count'];
			$scope.currentPage = 1;
			$scope.getPage(json['count']);
		});
	}

	/*分页*/
	$scope.changePage = function(p) {
		$scope.data.selectedPage = p;
		archivesService.search($scope.search,$scope.limit, p, $scope.app_id, function(json) {
			$scope.list = json.list;
			$scope.count = json.count;
			$scope.currentPage = p;
			$scope.getPage(json.count);
		});
	};
	$scope.getPage = function(count) {
		$scope.pageList = [];
		var limit = 20; //返回的条数
		$scope.totalPage = parseInt(count / limit); //总页数
		$scope.totalPage += count % limit >= 1 ? 1 : 0; //判断页数是否是整数
		var start = ($scope.currentPage - 2) >= 1 ? $scope.currentPage - 2 : 1; //首页
		var end = ($scope.currentPage + 2) <= $scope.totalPage ? $scope.currentPage + 2 : $scope.totalPage; //尾页

		$scope.frontdotShow = start > 1 ? true : false; //前面的省略号
		$scope.backdotShow = end < $scope.totalPage ? true : false; //后面的省略号
		for (var i = start; i <= end; i++) {
			$scope.pageList.push({
				number: i,
				active: i == $scope.currentPage ? 'active' : ''
			}); //给点击的按钮添加class
			console.log(count);
		}
	};

	$scope.delete = function(archives) {
        var c = confirm("确定要删除吗？");
        if (c == true)
        {
            archivesService.delete(archives.code, $scope.app_id, function(json) {
                if (json.status) {
                    $scope.getList();
                }
            });
        }

	}

	$scope.import = function(  ){
        var path = angular.element('#filepath').val();
        archivesService.import(path, $scope.app_id, function( json ){
            if(json)
                alert('导入成功');
            else
                alert('导入失败，请重新导入');
        });
    }
}


function archivesEditController($scope, $routeParams, $window, $location, $http, archivesService,orderService,callCenterService) {

	$scope.code = $routeParams.code;
	$scope.app_id = $routeParams.app_id;
	$scope.pageType = 'edit';
	if ($scope.code == 0) {
		$scope.pageType = 'create';
	}

	if ($scope.pageType == 'edit') {
		archivesService.find_one($scope.code, $scope.app_id, function(json) {
			$scope.archives = json;
            $scope.getServicePlanList(json.code);
			$scope.getStreet(json.xingzheng_code);
			$scope.getArea(json.jiedao_code);
		});
	}

	$scope.getRegion = function(code) {
			archivesService.getRegion(code,$scope.app_id, function(json) {
				$scope.region = json;
			});
		}
	$scope.getRegion(0);
	$scope.getStreet = function(code) {
		archivesService.getRegion(code,$scope.app_id,function(json){
			$scope.streets = json;
		});
	};
	$scope.getArea = function(code) {
        archivesService.getRegion(code,$scope.app_id,function(json){
			$scope.areas = json;
		});
	};

	$scope.edit = function(data) {
        if(typeof data.xingzheng_title == "undefined" || data.xingzheng_title ==""){
            angular.forEach($scope.region,function(array){
                if(array.code == data.xingzheng_code){
                    data.xingzheng_title = array.title;
                    data.xingzheng = array.title;
                }
            })
        }
        if(typeof data.jiedao_title == "undefined" || data.jiedao_title ==""){
            angular.forEach($scope.streets,function(array){
                if(array.code == data.jiedao_code){
                    data.jiedao_title = array.title;
                    data.jiedao = array.title;
                }
            })
        }
        if(typeof data.shequ_title == "undefined" || data.shequ_title ==""){
            angular.forEach($scope.areas,function(array){
                if(array.code == data.shequ_code){
                    data.shequ_title = array.title;
                    data.shequ = array.title;
                }
            })
        }
		archivesService.add(data,$scope.manageId, $scope.app_id, function(json) {
			if (json.status) {
				$location.path('/archives');
			}
		}, $scope.pageType);
	};

    //此处开始为生成新的服务计划 代码
    $scope.getserviceType1 = function(code){
        orderService.serviceListAll(code,function(d){
            $scope.serviceList1 = d.list;
            $scope.serviceList3=[];

        });
    }
    $scope.getserviceType2 = function(code){
        orderService.serviceListAll(code,function(d){
            $scope.serviceList2 = d.list;
            $scope.filterCompanyList = '';
            $scope.serviceList3=[];
        });
    }
    $scope.getserviceType3 = function(code){
        orderService.serviceListAll(code,function(d){
            $scope.serviceList3 = d.list;
            $scope.filterCompanyList = [];
        });
    };

    $scope.getCompanyList = function (code) {
        callCenterService.getCompany(code, $scope.app_id, function (json) {
            $scope.companyList = json['list'];
        });
    };
    $scope.getCompanyList();

    $scope.getserviceType1('0');
    $scope.newPlanTag =false;
    $scope.addServicePlan = function(){
        $scope.newPlanTag = true ;
    }
    $scope.AddNewPlan = function (archives,data){

        if(archives.name==""|| typeof archives.name == 'undefined'|| !archives.name  ){
            alert("请输入联系人");
            return;
        }
        if(archives.phone_mob==""|| typeof archives.phone_mob == 'undefined'|| !archives.phone_mob  ){
            alert("请输入联系人电话");
            return;
        }
        if(data.serviceType3==""|| typeof data.serviceType3 == 'undefined'|| !data.serviceType3  ){
            alert("请选择服务项目");
            return;
        }
        var manager = JSON.parse( localStorage.getItem(sessionStorage.getItem("who")+"manager") );
        var param = {} ;
        param.name = archives.name;
        param.phone = archives.phone_mob;
        param.address = archives.xingzheng_title+archives.jiedao_title+archives.shequ_title+archives.address;
        param.archives_code = archives.code;
        //Admin发布订单 By Nie

        if (typeof data.selected_company === 'undefined' || !data.selected_company) {
            alert('请选择受理企业！');
            return;
        }else{

            param.selected_company_code = typeof data.selected_company.code === 'undefined' || !data.selected_company.code ? '' : data.selected_company.code;
            param.selected_company_name = typeof data.selected_company.name === 'undefined' || !data.selected_company.name ? '' : data.selected_company.name;
            param.selected_company_phone = typeof data.selected_company.telephone === 'undefined' || !data.selected_company.telephone ? '' : data.selected_company.telephone;
        }

        param.serviceType1_code=typeof data.serviceType1!= "undefined" && data.serviceType1!= "" ? data.serviceType1.code:'';
        param.serviceType1_title=typeof data.serviceType1!= "undefined" && data.serviceType1!= "" ?data.serviceType1.title:'';
        param.serviceType2_code=typeof data.serviceType2!= "undefined" && data.serviceType2!= "" ?data.serviceType2.code:'';
        param.serviceType2_title=typeof data.serviceType2!= "undefined" && data.serviceType2!= "" ?data.serviceType2.title:'';
        param.serviceType3_code=typeof data.serviceType3!= "undefined" && data.serviceType3!= "" ?data.serviceType3.code:'';
        param.serviceType3_title=typeof data.serviceType3!= "undefined" && data.serviceType3!= ""?data.serviceType3.title:'';
        param.serviceType1= typeof data.serviceType1!= "undefined" && data.serviceType1!= "" ?data.serviceType1.code:'';
        param.serviceType2= typeof data.serviceType1!= "undefined" && data.serviceType2!= "" ?data.serviceType2.code:'';
        param.serviceType3= typeof data.serviceType1!= "undefined" && data.serviceType3!= "" ?data.serviceType3.code:'';

        orderService.addOrder(param, $scope.app_id, function(json) {
            alert("添加订单成功！");
            $scope.getServicePlanList(archives.code);
        });

    }
    $scope.getServicePlanList = function(code){

        $scope.order = [] ;
        $scope.newPlanTag =false;
        $scope.limit = 10 ;
        $scope.currentPage = 1 ;
        $scope.archivesOrderData = {
            archives_code : code,
            limit : 10 ,
            page : 1
        };
        orderService.list($scope.archivesOrderData,$scope.limit,$scope.currentPage,$scope.app_id,function(json){
            console.log(123);
            $scope.archivesOrderList = json.list;
            $scope.count = json.count;
            $scope.currentPage = 1;
            $scope.getPage(json.count);
        });
    };

    $scope.changePage = function(p) {
        $scope.archivesOrderData.page = p;
        orderService.list($scope.archivesOrderData, function(json) {
            $scope.archivesOrderList = json.list;
            $scope.count = json.count;
            $scope.currentPage = p;
            $scope.getPage(json.count);
        });
    };
    $scope.getPage = function(count) {
        $scope.pageList = [];
        var limit = $scope.archivesOrderData.limit; //返回的条数
        $scope.totalPage = parseInt(count / limit); //总页数
        $scope.totalPage += count % limit >= 1 ? 1 : 0; //判断页数是否是整数
        var start = ($scope.currentPage - 2) >= 1 ? $scope.currentPage - 2 : 1; //首页
        var end = ($scope.currentPage + 2) <= $scope.totalPage ? $scope.currentPage + 2 : $scope.totalPage; //尾页

        $scope.frontdotShow = start > 1 ? true : false; //前面的省略号
        $scope.backdotShow = end < $scope.totalPage ? true : false; //后面的省略号
        for (var i = start; i <= end; i++) {
            $scope.pageList.push({
                number: i,
                active: i == $scope.currentPage ? 'active' : ''
            }); //给点击的按钮添加class
        }
    };

}

function getCurrentYear(){
	var currentDate=new Date();
	return currentDate.getFullYear();
}